<template>
  <div class="question-list">
    <template>
      <div class="create-box">
        <!-- <el-button
          v-if="
            !isWriteRole &&
            tableStatus &&
            tableStatus.isLapse === '1' &&
            tableStatus.isStatus === '2' &&
            tableStatus.frozen == '1'
          "
          type="primary"
          size="mini"
          @click="$emit('create')"
          >增加质疑</el-button
        > -->
        <el-button
          v-if="permissionController('send::challenge')"
          type="primary"
          size="mini"
          @click="$emit('create')"
          style="margin-bottom: 12px"
          >增加质疑</el-button
        >
      </div>
      <div v-for="(i, index) in tableData" :key="index">
        <div class="title">
          <span>{{ `${index + 1} ${i[0].queryMethod == '0' ? '自动质疑' : '手动质疑'}` }}</span>
        </div>
        <el-table :data="i">
          <el-table-column type="index" label="#" align="center" />
          <el-table-column label="表名称" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.tableName || '/' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="变量名" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.variableName || '/' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="变量值" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.variableValue || '/' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="质疑说明" align="center">
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.queryContent.length > 10"
                class="item"
                effect="light"
                :content="scope.row.queryContent"
                placement="bottom-start"
              >
                <span>{{ `${scope.row.queryContent.substring(0, 10)}...` }}</span>
              </el-tooltip>
              <span v-else>{{ scope.row.queryContent }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="event" label="操作" align="center">
            <template v-slot="scope">
              {{ eventEnums[scope.row.event] }}
            </template>
          </el-table-column>
          <el-table-column prop="createBy" label="操作人" align="center">
            <template slot-scope="scope">
              {{ scope.row.roleId == -1 ? 'SYSTEM' : scope.row.createBy }}
            </template>
          </el-table-column>
          <el-table-column label="角色" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.roleId == -1 ? 'SYSTEM' : scope.row.roleName }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="时间" width="150" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime ? scope.row.createTime.replaceAll('T', ' ') : '' }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="btn">
          <!-- 添加备注 -->
          <!-- <template v-if="isWriteRole ? false : i[0].status < 3"> -->
          <!-- <template v-if="i[0].status < 3">
            <el-popover placement="top-end" width="275" trigger="click" v-model="i[0].addRemarkVisible">
              <div class="title-popover">
                <div><span class="title-icon">*</span> 备注：</div>
                <div>
                  <el-input size="mini" :clearable="true" v-model="addText" placeholder=""></el-input>
                </div>
              </div>
              <div style="text-align: right; margin: 0">
                <el-button :disabled="!addText" type="primary" size="mini" @click="onclick('add', i)">确定</el-button>
              </div>
              <el-button slot="reference" size="mini" type="primary">添加备注</el-button>
            </el-popover>
          </template> -->
          <!-- 回复质疑 -->
          <!-- <template v-if="isWriteRole ? i[0].status < 3 : false"> -->
          <span
            v-if="i[0].status < 3 && permissionController('subject::info::handle::challenge') && i.length !== 2 "
            style="margin-right: 4px"
          >
            <el-popover placement="top-end" width="275" trigger="click" v-model="i[0].replyQueryVisible">
              <div class="title-popover">
                <span class="title-icon">*</span> 回复：
                <el-input size="mini" :clearable="true" v-model="replyText" placeholder=""></el-input>
              </div>
              <div style="text-align: right; margin: 0">
                <el-button :disabled="!replyText" type="primary" size="mini" @click="onclick('reply', i)"
                  >确定</el-button
                >
              </div>
              <el-button slot="reference" size="mini" type="primary">回复质疑</el-button>
            </el-popover>
          </span>
          <!-- 关闭质疑 -->
          <!-- <template v-if="isShowClose(i)"> -->
          <template v-if="i[0].status < 3 && permissionController('close::challenge')">
            <el-popover placement="top-end" width="300" trigger="click" v-model="i[0].closeReasonVisible">
              <div class="title-popover">
                <div>
                  <span class="title-icon">*</span> 关闭原因：
                  <el-select size="mini" v-model="closeText" placeholder="" :clearable="true">
                    <el-option v-for="item in closeOptions" :key="item.value" :label="item.value" :value="item.value">
                    </el-option>
                  </el-select>
                </div>
                <div style="margin-top: 12px">
                  <el-checkbox v-model="requestionAgainChecked" style="margin-left: 12px">
                    <span style="font-size: 0.75rem"> 再质疑 </span>
                  </el-checkbox>
                </div>
              </div>
              <div style="text-align: right; margin: 0">
                <el-button :disabled="!closeText" type="primary" size="mini" @click="onclick('close', i)"
                  >确定</el-button
                >
              </div>
              <el-button slot="reference" size="mini" type="primary">关闭质疑</el-button>
            </el-popover>
          </template>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import { permissionController } from '@/utils/index'
export default {
  props: {
    tableStatus: {
      type: Object,
    },
    tableField: {
      type: Object,
    },
    exOptions: {
      type: Object,
    },
    queryType: {
      type: String,
    },
    variableName: {
      type: String,
    },
    dialogQuestionVisible: {
      type: Boolean,
    },
    queryListData: {
      type: Array,
    },
  },
  data() {
    return {
      loading: null,
      tableData: null,
      addText: '',
      replyText: '',
      closeOptions: [
        {
          value: '已确认',
        },
        {
          value: 'EC更新',
        },
        {
          value: '数据更正',
        },
        {
          value: '无需操作',
        },
        {
          value: '主动关闭',
        },
        {
          value: '系统关闭(old)',
        },
      ],
      closeText: '',
      list: null,
      eventEnums: {
        1: '创建质疑',
        2: '回复质疑',
        3: '质疑备注',
        4: '关闭质疑',
      },
      requestionAgainChecked: false,
    }
  },
  components: {},
  computed: {
    ...mapState({
      subjectInfo: state => state.treatment.subjectInfo,
      visit: state => state.treatment.visit,
      table: state => state.treatment.table,
      subjectInfo: state => state.treatment.subjectInfo,
    }),
    ...mapGetters({
      findRole: 'treatment/findRole',
      isWriteRole: 'treatment/isWriteRole',
    }),
  },
  watch: {
    dialogQuestionVisible: {
      handler(val) {
        if (val) {
          console.log(this.queryListData, 'queryListData')
          this.queryListData.forEach(item => {
            item[0].addRemarkVisible = false
            item[0].replyQueryVisible = false
            item[0].closeReasonVisible = false
          })
          this.tableData = this.queryListData
        }
      },
      immediate: true,
      deep: true,
    },
  },

  methods: {
    ...mapMutations({
      upgrade: 'treatment/upgrade',
    }),
    ...mapActions('eCRFDetail', ['replyQueryAPI', 'remarkQueryAPI', 'closeQueryAPI']),
    ...mapActions('eCRFDetail', ['getQueryListAPI']),

    // isShowClose(i) {
    //   const { status, roleId, roleCode } = i[0]
    //   if (status >= 3 || roleId == '-1') {
    //     return false
    //   }
    //   return this.findRole && this.findRole.code && this.findRole.code == roleCode
    // },

    permissionController,

    // 获取表格数据
    async getTableData() {
      let params = {}
      // 区分是表质疑，还是字段质疑，0是表质疑，1是字段质疑
      if (this.queryType === '0') {
        params = {
          id: this.tableStatus.formDataId,
        }
      } else {
        if (this.variableName) {
          params = {
            id: this.exOptions.tableFieldList[0].formDataId,
          }
        } else {
          params = {
            id: this.tableField.formFieldId,
          }
        }
      }
      const res = await this.getQueryListAPI({ params })
      if (res.code === 200) {
        res.data.forEach(item => {
          item[0].addRemarkVisible = false
          item[0].replyQueryVisible = false
          item[0].closeReasonVisible = false
        })
        this.tableData = res.data
      }
    },

    async onclick(type, i) {
      const data = {
        queryManageId: i[0].queryManageId,
        roleId: localStorage.getItem('roleId'),
        queryContent: '',
        environment: localStorage.getItem('environment'),
        queryType: this.queryType,
      }
      // 添加备注
      if (type == 'add') {
        data.queryContent = this.addText
        const res = await this.remarkQueryAPI({ data })
        if (res.code === 200) {
          this.$message.success('添加成功！')
          this.getTableData()
          this.addRemarkVisible = false
          this.addText = ''
        }
      }
      // 回复质疑
      else if (type == 'reply') {
        data.queryContent = this.replyText
        const res = await this.replyQueryAPI({ data })
        if (res.code === 200) {
          this.$message.success('回复成功！')
          this.getTableData()
          this.replyQueryVisible = false
          this.replyText = ''
        }
      }
      // 关闭质疑
      else if (type == 'close') {
        data.queryContent = this.closeText
        const res = await this.closeQueryAPI({ data })
        if (res.code === 200) {
          this.$message.success('关闭成功！')
          this.getTableData()
          this.closeReasonVisible = false
          this.closeText = ''
          if (this.requestionAgainChecked) {
            this.$emit('create')
          }
        }
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.title-popover {
  font-size: 0.75rem;
  margin: 0.5rem 0;
  .title-icon {
    color: #f56c6c;
  }
}
.el-input {
  width: 12rem;
}
.question-list {
  .create-box {
    text-align: left;
  }
  .title {
    text-align: left;
    color: #303133;
    font-weight: 700;
    font-size: 14px;
    line-height: 26px;
  }
  .btn {
    margin: 0.5rem 0 3rem;
    text-align: right;
    &:last-child {
      margin: 0.5rem 0 0;
    }
  }

  .loading-box {
    width: 100%;
    height: 30vh;
  }
}
</style>
